package com.healthcarex.hip.saas.security.vo;

import com.healthcarex.hip.saas.security.model.SysRole;
import com.healthcarex.hip.saas.security.model.SysUser;
import lombok.Getter;
import lombok.Setter;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.authority.SimpleGrantedAuthority;
import org.springframework.security.core.userdetails.UserDetails;

import java.util.ArrayList;
import java.util.Collection;
import java.util.List;

/**
 * @author  ChenPan
 * @date   2018/6/25 16:35
 * description:
 */
public class AuthUserDetail extends SysUser implements UserDetails {

    public AuthUserDetail(SysUser user, List<SysRole> roles) {
        this.setId(user.getId());
        this.setUsername(user.getUsername());
        this.setPassword(user.getPassword());
        this.setStatus(user.getStatus());
        this.setNickName(user.getNickName());
        this.setLastLoginTime(user.getLastLoginTime());
        this.setDeptCode(user.getDeptCode());
        this.setDeptName(user.getDeptName());
        this.setOrgCode(user.getOrgCode());
        this.setOrgName(user.getOrgName());
        this.setGenderCode(user.getGenderCode());
        this.setGenderName(user.getGenderName());
        this.setPhone(user.getPhone());
        this.setEmail(user.getEmail());
        this.setTheme(user.getTheme());
        this.setAvatar(user.getAvatar());
        this.setDescription(user.getDescription());

        this.setRoleList(roles);
    }

    @Getter
    @Setter
    private List<SysRole> roleList = new ArrayList<>();

    @Override
    public Collection<? extends GrantedAuthority> getAuthorities() {
        List<GrantedAuthority> authorityList = new ArrayList<>();
        for (SysRole role : roleList) {
            authorityList.add(new SimpleGrantedAuthority(role.getRoleCode()));
        }
        return authorityList;
    }

    @Override
    public boolean isAccountNonExpired() {
        return true;
    }

    @Override
    public boolean isAccountNonLocked() {
        return !STATUS_LOCK.equals(getStatus());
    }

    @Override
    public boolean isCredentialsNonExpired() {
        return true;
    }

    @Override
    public boolean isEnabled() {
        return STATUS_VALID.equals(getStatus());
    }
}
